<template>
  <div class="equipment-management">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="设备名称">
          <el-input
              v-model="searchForm.name"
              placeholder="输入设备名称"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="所属部门">
          <el-select
              v-model="searchForm.department"
              placeholder="选择部门"
              clearable
          >
            <el-option
                v-for="item in departmentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="安放位置">
          <el-input
              v-model="searchForm.location"
              placeholder="输入位置"
              clearable
              @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="设备状态">
          <el-select
              v-model="searchForm.status"
              placeholder="选择状态"
              clearable
          >
            <el-option
                v-for="item in statusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="name" label="设备名称" width="180" />
        <el-table-column prop="department" label="所属部门" width="120" />
        <el-table-column prop="location" label="安放位置" width="180" />
        <el-table-column prop="status" label="设备状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button
                size="small"
                type="primary"
                @click="showDetail(row)"
            >详细信息</el-button
            >
            <el-button
                size="small"
                type="success"
                @click="showMaintenance(row)"
            >养护计划</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 详细信息对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="设备详细信息"
        width="50%"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="设备名称">{{
            currentEquipment.name
          }}</el-descriptions-item>
        <el-descriptions-item label="设备编号">{{
            currentEquipment.code || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="所属部门">{{
            currentEquipment.department
          }}</el-descriptions-item>
        <el-descriptions-item label="安放位置">{{
            currentEquipment.location
          }}</el-descriptions-item>
        <el-descriptions-item label="设备状态">
          <el-tag :type="getStatusTagType(currentEquipment.status)">
            {{ getStatusText(currentEquipment.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="购置日期">{{
            currentEquipment.purchaseDate || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="设备型号">{{
            currentEquipment.model || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="生产厂家">{{
            currentEquipment.manufacturer || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="负责人">{{
            currentEquipment.principal || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{
            currentEquipment.contact || '-'
          }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{
            currentEquipment.remark || '无'
          }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 养护计划对话框 -->
    <el-dialog
        v-model="maintenanceDialogVisible"
        title="设备养护计划"
        width="60%"
    >
      <div v-if="currentEquipment.maintenancePlans?.length">
        <el-timeline>
          <el-timeline-item
              v-for="(plan, index) in currentEquipment.maintenancePlans"
              :key="index"
              :timestamp="plan.date"
              placement="top"
          >
            <el-card>
              <h4>{{ plan.title }}</h4>
              <p>{{ plan.content }}</p>
              <p>负责人: {{ plan.principal }}</p>
              <p>
                状态:
                <el-tag
                    :type="plan.status === 'completed' ? 'success' : 'warning'"
                >
                  {{ plan.status === 'completed' ? '已完成' : '待执行' }}
                </el-tag>
              </p>
            </el-card>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div v-else>
        <el-empty description="暂无养护计划" />
      </div>
      <template #footer>
        <el-button @click="maintenanceDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="addMaintenancePlan"
        >新增计划</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 搜索表单
const searchForm = ref({
  name: '',
  department: '',
  location: '',
  status: ''
})

// 部门选项
const departmentOptions = ref([
  { value: 'production', label: '生产部' },
  { value: 'logistics', label: '物流部' },
  { value: 'quality', label: '质检部' },
  { value: 'rd', label: '研发部' },
  { value: 'hr', label: '人力资源部' }
])

// 状态选项
const statusOptions = ref([
  { value: 'normal', label: '正常' },
  { value: 'maintenance', label: '维护中' },
  { value: 'fault', label: '故障' },
  { value: 'scrapped', label: '报废' }
])

// 表格数据
const tableData = ref([])

// 加载状态
const loading = ref(false)

// 分页信息
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 当前选中的设备
const currentEquipment = ref({})

// 对话框可见性
const detailDialogVisible = ref(false)
const maintenanceDialogVisible = ref(false)

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'normal':
      return 'success'
    case 'maintenance':
      return 'warning'
    case 'fault':
      return 'danger'
    case 'scrapped':
      return 'info'
    default:
      return ''
  }
}

// 获取状态文本
const getStatusText = (status) => {
  const option = statusOptions.value.find(item => item.value === status)
  return option ? option.label : status
}

// 查询设备列表
const fetchEquipmentList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    const mockData = Array.from({ length: 50 }, (_, i) => ({
      id: i + 1,
      name: `设备-${i + 1}`,
      code: `EQ-${1000 + i}`,
      department: departmentOptions.value[i % departmentOptions.value.length].value,
      location: ['A区', 'B区', 'C区', 'D区'][i % 4] + `-${(i % 20) + 1}号位`,
      status: statusOptions.value[i % statusOptions.value.length].value,
      purchaseDate: `202${i % 3}-0${(i % 9) + 1}-${(i % 28) + 1}`,
      model: `MODEL-${i % 5}`,
      manufacturer: ['厂商A', '厂商B', '厂商C'][i % 3],
      principal: ['张三', '李四', '王五'][i % 3],
      contact: `138${Math.floor(10000000 + Math.random() * 90000000)}`,
      remark: i % 4 === 0 ? '需要定期检查' : '',
      maintenancePlans: i % 3 === 0 ? [] : [
        {
          date: `2023-0${(i % 9) + 1}-${(i % 28) + 1}`,
          title: '定期维护',
          content: '更换滤芯，检查电路',
          principal: '李四',
          status: i % 2 === 0 ? 'completed' : 'pending'
        }
      ]
    }))

    // 应用筛选条件
    let filteredData = [...mockData]
    if (searchForm.value.name) {
      filteredData = filteredData.filter(item =>
          item.name.includes(searchForm.value.name)
      )
    }
    if (searchForm.value.department) {
      filteredData = filteredData.filter(item =>
          item.department === searchForm.value.department
      )
    }
    if (searchForm.value.location) {
      filteredData = filteredData.filter(item =>
          item.location.includes(searchForm.value.location)
      )
    }
    if (searchForm.value.status) {
      filteredData = filteredData.filter(item =>
          item.status === searchForm.value.status
      )
    }

    // 更新分页信息
    pagination.value.total = filteredData.length

    // 分页处理
    const start = (pagination.value.currentPage - 1) * pagination.value.pageSize
    const end = start + pagination.value.pageSize
    tableData.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取设备列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchEquipmentList()
}

// 重置查询
const resetSearch = () => {
  searchForm.value = {
    name: '',
    department: '',
    location: '',
    status: ''
  }
  handleSearch()
}

// 显示详细信息
const showDetail = (row) => {
  currentEquipment.value = row
  detailDialogVisible.value = true
}

// 显示养护计划
const showMaintenance = (row) => {
  currentEquipment.value = row
  maintenanceDialogVisible.value = true
}

// 新增养护计划
const addMaintenancePlan = () => {
  ElMessage.info('新增养护计划功能待实现')
  // 实际项目中这里应该打开一个新的表单对话框
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  fetchEquipmentList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  fetchEquipmentList()
}

// 初始化加载数据
onMounted(() => {
  fetchEquipmentList()
})
</script>

<style scoped>
.equipment-management {
  padding: 20px;
}

.search-container {
  background-color: #f5f7fa;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 4px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
}

.table-container {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>